package com.gzsxy.esjy.service.statistical.schedule;

import com.gzsxy.esjy.service.statistical.service.StatisicalService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 定时任务（凌晨12：00统计前一天的订单数据与用户数据并初始化统计表）
 * @date 2022/3/18 20:40
 */

@Component
@ConditionalOnProperty(name = "data-share.enabled",havingValue = "true")
public class ScheduledTask {

    private final static Logger log = LoggerFactory.getLogger(ScheduledTask.class);

    private static final SimpleDateFormat DATE_FORMAT =  new SimpleDateFormat( "yyyy-MM-dd ");


    @Autowired
    private StatisicalService statisicalService;

    private volatile boolean isRun = false;


    /**
     * @description: 每天凌晨12：00执行
     * @param
     * @return
     */
//    @Scheduled(cron = "0 0/1 * * * ?")
    @Scheduled(cron = "0 0 0 */1 * ?")
    public void init(){
        if (!isRun){
            isRun = true;
            try {
                log.info("定时任务执行开始，当前时间【{}】", DATE_FORMAT.format(new Date()));
                //统计昨天整体的销量情况数据
                statisicalService.LoginStatistics();
            } catch (Exception e) {
                log.error("定时任务执行失败",e);
            } finally {
                //初始化系统所有商家今日的订单数据统计表
                statisicalService.InitStatisicals(DATE_FORMAT.format(new Date()));
            }
            isRun = false;
        }
    }
}
